<template>
  <div class="text-center q-pa-md full-width full-height">
    <!-- <Player url="rtmp://live.hkstv.hk.lxdns.com/live/hks2" isMainScreen @playerClick="playerClick" /> -->
    <div style="height: 88%; width: 100%">
      <!-- <Player ref="mainPlayer" :url="mainUrl" isMainScreen/> -->
      <div id="main-player" ref="mainPlayer"/>
    </div>
    <div class="text-center q-pa-md">
      <QBtnGroup outline>
        <QBtn icon="camera_alt" color="secondary" @click="snapShot()"/>
        <QBtn icon="restore" color="secondary" @click="mainUrl = mainUrl.split('zoomhelper')[0]"/>
        <QBtn color="secondary" @click="zoomVideo('leftup')">
          <QIcon name="call_received" class="rotate-90"/>
        </QBtn>
        <QBtn color="secondary" icon="call_received" @click="zoomVideo('leftdown')"/>
        <QBtn color="secondary" icon="call_made" @click="zoomVideo('rightup')"/>
        <QBtn color="secondary" @click="zoomVideo('rightdown')">
          <QIcon name="call_made" class="rotate-90"/>
        </QBtn>
      </QBtnGroup>
    </div>
    <QModal v-model="dialogShow" :content-css="{maxWidth: '80vw', maxHeight: '80vh'}">
      <canvas id="canvasDemo" ref="canvasDemo" :width="imgWidth" :height="imgHeight"/>
      <!-- <img src="../assets/test.png" :width="imgWidth" :height="imgHeight" /> -->
      <QBtn color="primary" @click="handleSubmit()" label="Submit"/>
      <QBtn color="primary" @click="dialogShow = false" label="Close"/>
    </QModal>
  </div>
</template>

<script>
import Player from './Player'
import { dom } from 'quasar'
const { height, width } = dom
export default {
  name: 'MainPlayer',
  props: {
    // users: { type: Array, default: () => ([]) },
    mainUrl: { type: String, default: '' }
  },
  components: { Player },
  data: () => ({
    rtmpBaseUrl: `rtmp://${window.location.host.split(':')[0]}/live/`,
    // rtmpBaseUrl: `rtmp://test2.goolton.com/live/`,
    testUrl: 'http://test2.goolton.com:8000',
    dialogShow: false,
    imgHeight: 0,
    imgWidth: 0,
    sketchpad: null,
    context: null,
    mainPlayer: null,
    playerConfig: {
      flashplayer: 'http://cdn.bdstatic.com/jwplayer/latest/cyberplayer.flash.swf',
      autostart: true,
      stretching: 'uniform',
      volume: 100,
      controls: true,
      rtmp: {
        reconnecttime: 5, // rtmp直播的重连次数
        bufferlength: 1 // 缓冲多少秒之后开始播放 默认1秒
      },
      ak: '28c4f4cf125a461d81c76fa96d8b1422' // 公有云平台注册即可获得accessKey
    }
  }),
  mounted () {
    // this.getOnlineUsers()
    // this.getMainUrl(this.users)
  },
  watch: {
    mainUrl: {
      handler () {
        this.setupPlayer()
      },
      deep: true
    }
  },
  methods: {
    async setupPlayer () {
      if (!this.mainUrl) return
      // this.playerConfig.file = this.url || ''
      const playerConfig = Object.assign({}, this.playerConfig)
      playerConfig.file = this.mainUrl
      playerConfig.height = height(this.$refs.mainPlayer.parentElement) - 10
      playerConfig.width = width(this.$refs.mainPlayer.parentElement) - 10
      if (this.mainPlayer) {
        if (this.mainPlayer.getPlaylistItem(0) && this.mainPlayer.getPlaylistItem(0).file !== this.mainUrl) {
          this.mainPlayer.setup(playerConfig)
        }
      } else {
        this.mainPlayer = window.cyberplayer('main-player').setup(playerConfig)
      }
    },
    async zoomVideo (region) {
      // const {data} = await this.$http.get(`http://${location.host.split(':')[0]}:8000/api/zoom` /* `${this.testUrl}/api/zoom ` */, {
      //   url: this.mainUrl,
      //   region
      // })
      const { data } = await this.$http.get(`http://${window.location.host.split(':')[0]}:8000//api/zoom`, {
        params: {
          url: this.mainUrl,
          region
        }
      })
      if (data.errormsg) {
        this.$q.dialog({
          title: '错误！',
          message: `${data.errormsg}`
        })
      } else {
        const url = this.mainUrl.slice(0)
        this.mainUrl = url.split('zoomhelper')[0] + 'zoomhelper'
      }
    },
    async snapShot () {
      // const {data} = await this.$http.get(`http://${location.host.split(':')[0]}:8000/api/snapshot`/* `${this.testUrl}/api/snapshot` */, {
      //   url: this.mainUrl
      // })
      const { data } = await this.$http.get(`http://${window.location.host.split(':')[0]}:8000/api/snapshot`, {
        params: {
          url: this.mainUrl
        }
      })
      const snapedImage = new Image()
      snapedImage.crossOrigin = 'Anonymous'
      snapedImage.onload = () => {
        this.imgHeight = snapedImage.height > document.body.clientHeight * 0.8 ? document.body.clientHeight * 0.8 : snapedImage.height
        // var imgHeight = 100
        this.imgWidth = snapedImage.width * this.imgHeight / snapedImage.height
        this.sketchpad = this.sketchpad || new window.Sketchpad({
          element: '#canvasDemo',
          width: this.imgWidth,
          height: this.imgHeight
        })
        this.sketchpad.color = '#BF0A10'
        this.sketchpad.width = this.imgWidth
        this.sketchpad.height = this.imgHeight
        const canvas = document.getElementById('canvasDemo')
        this.context = this.context || canvas.getContext('2d')
        this.context.clearRect(0, 0, canvas.width, canvas.height)
        // const context = window.que('#canvasDemo')[0].getContext('2d')
        setTimeout(() => { this.context.drawImage(snapedImage, 0, 0) }, 1000)
        this.dialogShow = true
        // document.appendChild(snapedImage)
      }
      snapedImage.src = `http://${location.host.split(':')[0]}:8000/${data.imageUrl}`
      // snapedImage.src = `${this.testUrl}/${data.imageUrl}`
    },
    async handleSubmit () {
      this.canvas2blobPollyfill()
      const canvas = this.$refs.canvasDemo
      canvas.toBlob(async blob => {
        const urlArray = this.mainUrl.split('/')
        const userId = this.mainUrl ? urlArray[urlArray.length - 1].split('AAA')[0] : 0
        const senderId = this.$q.cookies.get('userID')
        const params = new FormData()
        const jsonPkg = {
          appKey: 4,
          commonKey: 100,
          data: {
            contentType: '3',
            receiverID: userId,
            senderID: senderId,
            msgType: '1',
            gpsLatitude: this.$q.cookies.get('gpsLatitude'),
            gpsLongtitude: this.$q.cookies.get('gpsLongtitude')
          }
        }
        params.append('gdData', JSON.stringify(jsonPkg))
        params.append('mediaFile', blob, 'image.png')
        /* const result =  */await this.$http.post('./jsonGateway.php', params)
        this.dialogShow = false
      })
    },
    canvas2blobPollyfill () {
      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
              len = binStr.length,
              arr = new Uint8Array(len)
            for (var i = 0; i < len; i++) {
              arr[i] = binStr.charCodeAt(i)
            }
            callback(new Blob([arr], { type: type || 'image/png' }))
          }
        })
      }
    }
  },

  beforeDestroy () {
    console.log('TCL: beforeDestroy -> beforeDestroy', 'aaaa')
  }
}
</script>

<style lang="stylus">
</style>
